package com.exsun.gateway.jt809.kafka;

import com.exsun.gateway.jt809.common.DevInfoService;
import com.exsun.gateway.jt809.data.PushData;
import com.exsun.gateway.jt809.handler.cache.MediaListHandle;
import com.exsun.gateway.jt809.handler.SendMgrHandler;
import com.google.gson.reflect.TypeToken;
import exsun.jt808.data.config.jt808.Jt808ReceiveMsgTopic;
import exsun.jt808.data.config.jt809.Jt809MsgIdConfig;
import exsun.jt808.data.jt809_data.BasicVehicleInfo;
import exsun.jt808.data.jt809_data.SendBaseEntity;
import exsun.jt808.data.jt809_data.video.main.UpFileListMsg;
import exsun.jt808.data.jt809_data.video.main.UpRealVideoFileListReqAck;
import exsun.jt808.data.jt809_data.video.main.VideoFileInfo;
import exsun.jt808.data.jt809_data.video.slave.DownRealVideoFileListReq;
import exsun.jt808.data.kafka_data.KafkaJT808Data;
import exsun.jt808.data.upload_data.jt1078.MediaFileList;
import exsun.jt808.data.upload_data.jt1078.MediaListItem;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传音视频资源目录
 */
@Service
public class JT809KafkaVideoFileListHandler extends JT809KafkaHandleBase<MediaFileList>{
    private Logger logger = LoggerFactory.getLogger(JT809KafkaVideoFileListHandler.class);

    @Autowired
    private SendMgrHandler sendMgrHandler;

    @Autowired
    private DevInfoService devInfoService;

    //订阅媒体数据
    @KafkaListener(topics = Jt808ReceiveMsgTopic.MediaFileList, containerFactory = "mediaFileListFactory")
    public void batchMediaMsgConsumerListen(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) {
        try{
            //多媒体数据上传
            Type type = new TypeToken<KafkaJT808Data<MediaFileList>>(){}.getType();
            List<PushData> pushs =  super.done(records, type, (obj)->{
                SendBaseEntity entity = null;
                DownRealVideoFileListReq req = MediaListHandle.inst.get(obj.dvo);
                byte[] body = null;
                List<PushData> temp = new ArrayList<>();
                if(req != null){
                    //查询应答
                    entity = getRealVideoFileListReqAck(req, obj);
                    body = sendMgrHandler.jt809Encode.upRealVideoFileListReqAck((UpRealVideoFileListReqAck)entity);
                    logger.info("查询资源列表应答:{}", obj.dvo);
                }else {
                    BasicVehicleInfo basicVehicleInfo = devInfoService.getBasicVehicleInfo(obj.dvo);
                    entity = getAlarmFileList(basicVehicleInfo, obj);
                    if(entity == null)return temp;
                    body = sendMgrHandler.jt809Encode.upFileListMsg((UpFileListMsg)entity);
                }
                if(body == null){
                    logger.info("不上传资源列表:{}", obj.dvo);
                    return temp;
                }
                PushData pushData = new PushData(Jt809MsgIdConfig.UP_SEARCH_MSG, body);
                temp.add(pushData);
                return temp;
            });
            //发送错误，则不提交偏移量
            if(pushs == null)return;
            if(pushs.size() != 0){
                logger.info("上报资源列表上传：{}条", pushs.size());
            }
            ack.acknowledge();
        }catch(Exception e){
            logger.info(e.getMessage());
        }
    }

    /**
     * 查询列表应答
     * @param req
     * @param objs
     * @return
     */
    private SendBaseEntity getRealVideoFileListReqAck(DownRealVideoFileListReq req, MediaFileList objs){
        UpRealVideoFileListReqAck entity = new UpRealVideoFileListReqAck();
        entity.setBasicVehicleInfo(req.getBasicVehicleInfo());
        entity.setResult(0);
        entity.setVideoFileInfos(getFileList(objs.getMediaListItems()));
        return entity;
    }
    /**
     * 主动上传含有报警的资源
     * @param objs
     * @return
     */
    private SendBaseEntity getAlarmFileList(BasicVehicleInfo basicVehicleInfo, MediaFileList objs){
        UpFileListMsg entity = null;
        List<MediaListItem> temp = new ArrayList<>();
        for (MediaListItem item : objs.getMediaListItems()){
            if(!item.getAlarmHexStr().equals("0000000000000000")){
                temp.add(item);
            }
        }
        if(temp.size() == 0)return entity;
        entity = new UpFileListMsg();
        entity.setBasicVehicleInfo(basicVehicleInfo);
        entity.setVideoFileInfos(getFileList(temp));
        return entity;
    }

    private List<VideoFileInfo> getFileList(List<MediaListItem> items){
        List<VideoFileInfo> list = new ArrayList<>();
        VideoFileInfo fileInfo  = new VideoFileInfo();
        for(MediaListItem obj : items){
            fileInfo.setChannelId(obj.getChanelId());
            fileInfo.setStartTime(obj.getStartTime());
            fileInfo.setEndTime(obj.getEndTime());
            fileInfo.setAlarmType(obj.getAlarmHexStr());
            fileInfo.setMediaType(obj.getMediaType());
            fileInfo.setCodeType(obj.getCodeType());
            fileInfo.setStorageType(obj.getStorageType());
            fileInfo.setFileSize(obj.getFileSize());
            list.add(fileInfo);
        }
        return  list;
    }
}
